package JDBC.Day03;

import java.sql.*;

/**
 *  JDBC -- ResultSet处理结果集
 */
public class JDBCResultSet {
    public static void main(String[] args) {
        //1. 导入jar包
        // 将第三方厂商提供的数据库jar包放在新建的libs目录下
        // 右键点击libs目录，选择 Add as Library... 完成导入

        Connection conn = null;
        Statement stmt = null;
        ResultSet resultSet = null;
        try {
            //2. 注册驱动
            Class.forName("com.mysql.jdbc.Driver");

            //3. 获取数据库连接对象
            // 当数据库位于本机并且端口位3306时，可以省略该字段
            //conn = DriverManager.getConnection(
            //        "jdbc:mysql://localhost:3306/testdata", "root", "root");
            conn = DriverManager.getConnection("jdbc:mysql:///testdata", "root", "root");

            //4. 定义sql语句
            String sql = "SELECT * from student";

            //5. 获取执行sql的对象 Statement
            stmt = conn.createStatement();

            //6. 执行sql
            resultSet = stmt.executeQuery(sql);

            //7. 处理结果
            //7.1 让光标下移一行 并判断是否继续循环遍历
            while(resultSet.next()) {
                //7.2 获取数据
                int id = resultSet.getInt("id");
                String name = resultSet.getString("name");
                String gender = resultSet.getString("gender");
                String birthday = resultSet.getString("birthday");
                String insert_Time = resultSet.getString("insert_time");
                String address = resultSet.getString("address");

                System.out.println("id：" + id +
                        "，姓名：" + name +
                        "，性别：" + gender +
                        "，生日：" + birthday +
                        "，加入时间：" + insert_Time +
                        "，地址：" + address);

            }

        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
        } finally {
            //8. 释放资源
            if(resultSet != null) {
                try {
                    resultSet.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if(stmt != null) {
                try {
                    stmt.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }

            }
            if(stmt != null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
